package com.tianxin.workbao.workBao.Activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.view.WindowManager;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.application.BaseApplication;
import com.tianxin.workbao.workBao.bean.Appupdate;
import com.tianxin.workbao.workBao.dataProvide.ApkProvide;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.manager.DownLoadManager;
import com.tianxin.workbao.workBao.utils.common.ToastUtils;

import java.io.File;

import me.wangyuwei.particleview.ParticleView;


public class SplashActivity extends AppCompatActivity implements UpdateListViewListener {
    private ParticleView company_logo;
    private boolean isNeedUpdate = false;
    private ApkProvide apkProvide;
    private Appupdate appupdate;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_splash);

        checkApkVersion();
        company_logo = findViewById(R.id.company_logo);
        company_logo.setOnParticleAnimListener(() -> {
            if (isNeedUpdate == false) {
                startLogin();
            }
        });
        company_logo.startAnim();
    }

    private void checkApkVersion() {
        getApkProvide().getNew();
    }

    /**
     * start Login Activity
     */
    private void startLogin() {
        Intent loginIntent = new Intent(SplashActivity.this, LoginActivity.class);
        startActivity(loginIntent);
        SplashActivity.this.finish();
    }

    private void matchVersion() {
        if (appupdate == null) {
            showMessage("Apk 为空");
            return;
        }
        int versionCode = BaseApplication.getVersionCode(this);
        if (appupdate.getVersionnum() > versionCode) {
            isNeedUpdate = true;
            if (appupdate.getStatus() == 1) {
                //强行更新
                downLoadApk();
            } else {
                //显示 更新 Dialog
                showUpdateDialog();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public ApkProvide getApkProvide() {
        if (apkProvide == null) {
            apkProvide = new ApkProvide(this, this);
        }
        return apkProvide;
    }

    @Override
    public void showMessage(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void onRefreshData(Object result) {
        if (result instanceof Appupdate) {
            appupdate = (Appupdate) result;
            matchVersion();
        }
    }


    @Override
    public void onLoadMoreData(Object result) {

    }

    /**
     * 弹出对话框通知用户更新程序
     * 弹出对话框的步骤：
     * 1.创建alertDialog的builder.
     * 2.要给builder设置属性, 对话框的内容,样式,按钮
     * 3.通过builder 创建一个对话框
     * 4.对话框show()出来
     */

    protected void showUpdateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("版本升级");
        builder.setMessage(appupdate.getUpdatedeacription());
        builder.setPositiveButton("确定", (dialog, which) -> downLoadApk());
        builder.setNegativeButton("取消", (dialog, which) -> {
            dialog.dismiss();
            startLogin();
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    /**
     * 从服务器中下载APK
     */


    protected void downLoadApk() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
                    PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                return;
            }
        }
        final ProgressDialog pd;
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载更新");
        pd.setCanceledOnTouchOutside(false);
        pd.show();
        new Thread(()->{
            File file = DownLoadManager.getFileFromServer(appupdate.getDownurl(), pd);
            installApk(file);
            pd.dismiss();
        }).start();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            downLoadApk();
        } else {
            ToastUtils.showLong("你拒绝SD card 读写权限，系统无法自动更新");
        }
    }

    //安装apk
    protected void installApk(File file) {
        //判读版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) {
            //在AndroidManifest中的android:authorities值
            Uri apkUri = FileProvider.getUriForFile(this, "com.tianxin.workbao.workbao.fileprovider", file);
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
            startActivity(install);
        } else {
            if (Build.VERSION.SDK_INT < 23) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                startActivity(intent);
            } else {
                openFile(file);
            }
        }
    }

    public void openFile(File file) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction("android.intent.action.VIEW");
        String type = getMIMEType(file);
        intent.setDataAndType(Uri.fromFile(file), type);
        try {
            startActivity(intent);
        } catch (Exception ex) {
            ex.printStackTrace();
            ToastUtils.showLong("没有找到打开此类文件的程序");
        }

    }

    public String getMIMEType(File file) {
        String var2 = file.getName();
        String var3 = var2.substring(var2.lastIndexOf(".") + 1).toLowerCase();
        return MimeTypeMap.getSingleton().getMimeTypeFromExtension(var3);
    }

}
